package com.stylefeng.guns.core.util.appSecure;

import java.security.GeneralSecurityException;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Description:
 *
 * @author
 * @version 2.0
 * @since 2017/8/25
 */
public class AESUtil {

    private static final int IV_SIZE = 16;
    private static final int KEY_SIZE = 16;
    private static final int ITERATION_COUNT = 100;
    private static final String TRANSFORMATION = "AES/CBC/PKCS5PADDING";

    private static final byte[] IV = generateBytes("BroadDeep&Safe".getBytes(), IV_SIZE);
    private static final byte[] SALT = generateBytes("EverSec&BroadDeep$Mobile".getBytes(), KEY_SIZE);

    public static byte[] encrypt(byte[] data, String password) {
        return encryptData(data, IV, deriveKeySecurely(password, KEY_SIZE));
    }

    public static byte[] decrypt(byte[] data, String password) {
        return decryptData(data, IV, deriveKeySecurely(password, KEY_SIZE));
    }

    private static byte[] generateBytes(byte[] data, int size) {
        byte[] iv = new byte[size];
        int len = data.length;
        for (int i = 0; i < size; i++) {
            iv[i] = data[i % len];
        }
        return iv;
    }

    private static SecretKey deriveKeySecurely(String password, int keySizeInBytes) {
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), SALT, ITERATION_COUNT, keySizeInBytes * 8);
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
            return new SecretKeySpec(keyBytes, "AES");
        } catch (Exception e) {
            throw new RuntimeException("deriveKey", e);
        }

    }

    private static byte[] encryptOrDecrypt(byte[] data, SecretKey key, byte[] iv, boolean isEncrypt) {
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
            return cipher.doFinal(data);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("encryptOrDecrypt", e);
        }
    }

    private static byte[] encryptData(byte[] data, byte[] iv, SecretKey key) {
        return encryptOrDecrypt(data, key, iv, true);
    }

    private static byte[] decryptData(byte[] data, byte[] iv, SecretKey key) {
        return encryptOrDecrypt(data, key, iv, false);
    }

}
